<?php

use app\common\facade\CategoryFacade;
use think\Db;
use think\facade\Env;
use think\facade\Request;

define('SESSKEY_ADMIN_ID', 'adminId');
define('SESSKEY_ADMIN_NAME', 'adminname');
define('SESSKEY_ADMIN_LAST_TIME', 'adminLTime');
define('SESSKEY_ADMIN_AUTO_LOGIN', 'adminlogin');

function setLogin($user, $logintype = 1, $isApp = false)
{
    $time = time();
    session(SESSKEY_ADMIN_ID, $user['id']);
    session(SESSKEY_ADMIN_LAST_TIME, $time);
    session(SESSKEY_ADMIN_NAME, empty($user['realname']) ? $user['username'] : $user['realname']);
    if (!$isApp) {
        Db::name('Manager')->where('id', $user['id'])->update(array(
            'login_ip' => Request::ip(),
            'login_time' => $time
        ));
    }
    if ($logintype == 1) {
        user_log($user['id'], 'login', 1, '登录成功', 'manager');
    } else {
        user_log($user['id'], 'login', 1, '自动登录成功', 'manager');
    }
}

function clearLogin($log = true)
{
    $id = session(SESSKEY_ADMIN_ID);
    if ($log && !empty($id)) {
        user_log($id, 'logout', 1, '退出登录');
    }

    session(SESSKEY_ADMIN_ID, null);
    session(SESSKEY_ADMIN_NAME, null);
    session(SESSKEY_ADMIN_LAST_TIME, null);
    cookie(SESSKEY_ADMIN_AUTO_LOGIN, null);
}

function getMenus($force = false)
{
    $menus = cache('menus');
    if (empty($menus) || $force) {
        $list = Db::name('permission')->where('disable', 0)->order('parent_id ASC,sort_id ASC,id ASC')->select();
        $menus = array();
        foreach ($list as $item) {
            $menus[$item['parent_id']][] = $item;
        }
        if (config('channel_mode')) {
            $menus[2] = [];
            $topCates = CategoryFacade::getSubCategory(0);
            if (empty($topCates)) {
                $menus[2][] = [
                    'parent_id' => 2,
                    'name' => '栏目初始化',
                    'url' => 'Channel/init',
                    'key' => 'channel_index',
                    'icon' => 'ion-md-apps',
                    'sort_id' => 0,
                    'disable' => 0
                ];
            } else {
                foreach ($topCates as $cate) {
                    $menus[2][] = [
                        'parent_id' => 2,
                        'name' => $cate['title'],
                        'url' => 'Channel/index?channel_id=' . $cate['id'],
                        'key' => 'channel_index_' . $cate['id'],
                        'icon' => 'ion-md-apps',
                        'sort_id' => $cate['sort'],
                        'disable' => 0
                    ];
                }
            }
        }
        cache('menus', $menus, 1800);
    }
    return $menus;
}

function check_password($password)
{
    if (in_array($password, ['123456', '654321', 'admin', 'abc123', '123abc', '12345678', '123456789'])) {
        session('password_error', 1);
    } elseif (preg_match('/^([0-9])\\1*$/', $password)) {
        session('password_error', 2);
    } elseif (preg_match('/^[0-9]*$/', $password)) {
        session('password_error', 3);
    } elseif (preg_match('/^([a-zA-Z])\\1*$/', $password)) {
        session('password_error', 4);
    } else {
        session('password_error', null);
    }
}

function FU($url = '', $vars = '')
{

    $link = url($url, $vars);

    return str_replace(app()->getModulePath(), '', $link);
}

function delete_image($images)
{
    if (is_array($images)) {
        foreach ($images as $image) {
            delete_image($image);
        }
    } else {
        $images = str_replace('\\', '/', $images);

        if (strpos($images, '../') !== false) return;

        if (!empty($images) && strpos($images, '/uploads/') === 0) {
            @unlink('.' . $images);
        }
    }
}

function list_empty($col = 5, $content = '暂时没有记录')
{
    return '<tr><td colspan="' . $col . '" class="text-center text-muted">' . $content . '</td></tr>';
}

function ignore_array($val)
{
    if (is_array($val)) return '';
    return strval($val);
}

function wechat_is_official($type)
{
    if (in_array($type, ['wechat', 'subscribe', 'service'])) {
        return true;
    }
    return false;
}


function save_setting($data, $group = '')
{
    $settings = getSettings(true, false, false);
    $group = empty($group) ? [] : explode(',', $group);
    $configPath = Env::get('config_path') . DIRECTORY_SEPARATOR . 'app.php';
    $appConfig = file_get_contents($configPath);
    $isConfigChanged = false;
    foreach ($data as $k => $v) {
        if (substr($k, 0, 2) == 'v-') {
            $key = substr($k, 2);
            if (isset($settings[$key])) {
                if (!empty($group) && !in_array($settings[$key]['group'], $group)) {
                    continue;
                }
                if ($key == 'lang_data') {
                    $langs = [];
                    foreach ($v as $sk => $sv) {
                        if (empty($sv['name'])) {
                            unset($v[$sk]);
                            continue;
                        }
                        if (in_array($sv['name'], $langs)) continue;
                        $langs[] = $sv['name'];
                    }
                    if (json_encode($langs) != json_encode(config('allow_lang_list'))) {
                        $isConfigChanged = true;
                        $imploded = '';
                        if (!empty($v)) {
                            $imploded = "'" . implode("','", $langs) . "'";
                        }
                        $appConfig = preg_replace("/('allow_lang_list'\s*=>\s*)\[[',\s\w\-_]*\]\s*,/", '$1[' . $imploded . '],', $appConfig);
                    }
                    $defaultLang = $langs[0] ?? '';
                    if ($defaultLang != config('default_lang')) {
                        $appConfig = preg_replace("/('default_lang'\s*=>\s*)'[\w\-_]*'\s*,/", '$1\'' . $defaultLang . '\',', $appConfig);
                    }
                }
                if (is_array($v)) {
                    if (in_array($settings[$key]['type'], ['json', 'array'])) {
                        if ($settings[$key]['type'] == 'array') {
                            $v = array_values($v);
                        }
                        $v = json_encode($v, JSON_UNESCAPED_UNICODE);
                    } else {
                        $v = serialize($v);
                    }
                }
                if ($key == 'lang_switch') {
                    if ($v != config('lang_switch_on')) {
                        $isConfigChanged = true;
                        $appConfig = preg_replace("/('lang_switch_on'\s*=>\s*)(true|false)\s*,/", '$1' . ($v ? 'true' : 'false') . ',', $appConfig);
                    }
                }

                if ($settings[$key]['value'] != $v) {
                    Db::name('setting')->where('key', $key)->update(array('value' => $v));
                }
            }
        }
    }
    if ($isConfigChanged) {
        file_put_contents($configPath, $appConfig);
    }
    cache('setting', null);
    return true;
}

function writeEnv($key, $value)
{
    $envfile = Env::get('root_path') . '.env';
    $content = file_get_contents($envfile);
    $content = preg_replace('/^' . $key . '\s*=\s*[\w\|]+\s*$/m', "$key = $value", $content);
    file_put_contents($envfile, $content);
}

function writeConstants($key, $value)
{
    $path = Env::get('config_path') . DIRECTORY_SEPARATOR . 'constants.php';
    $config = config('constants.');
    if (empty($config) || !is_array($config)) $config = [];
    $config[$key] = $value;
    file_put_contents($path, "<\x3fphp\n\nreturn " . var_export($config, true) . ';');
}

//end file